//
//  MasterViewController.m
//  Porthole
//
//  Created by Dennis Chau on 12/8/11.
//  Copyright (c) 2011 Univeristy of Illinois at Chicago. All rights reserved.
//

#import "MasterViewController.h"
#import "DetailViewController.h"

@implementation MasterViewController

@synthesize GUITableData;
@synthesize detailViewController = _detailViewController;
#
#
#pragma mark Memory management
#
#
//////////////////////////////////////////////////////////////////////////////////////////////////
//
- (void) dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
//////////////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////////////
//
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}
//////////////////////////////////////////////////////////////////////////////////////////////////

#
#
#pragma mark - View lifecycle
#
#
//////////////////////////////////////////////////////////////////////////////////////////////////
//
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        NSLog(@"MasterVC :: configuring view controller .....");
        
        //Setup the title
        self.title = @"Custom UI Area";

        //If this is an iPad this code handles pop over stuff 
        if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) 
        {
            self.clearsSelectionOnViewWillAppear = NO;
            self.contentSizeForViewInPopover = CGSizeMake(320.0, 600.0);
        }

        //setup notification for when a GUI spec recieved
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setupCUAFromGUISpec:) name:@"SetupCUAFromGUISpec" object:nil];
    }
    return self;
}
//////////////////////////////////////////////////////////////////////////////////////////////////							

//////////////////////////////////////////////////////////////////////////////////////////////////
//
- (void)viewDidLoad
{
    [super viewDidLoad];
    NSLog(@"\tMasterVC :: view did load");

    //Setup the link to the data
    [ self.tableView setDataSource:self];
    [ self.tableView setDelegate:self];
    
    //Setup table styles
    int cellSize = 75;
    self.tableView.rowHeight = cellSize;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [UIColor blackColor];

    //Setup the GUITableData
    GUITableData = [[NSMutableArray alloc]init];    
    [GUITableData addObjectsFromArray:[NSArray arrayWithObjects: @"0:1:Button:PushMe:PushMe:|", @"1:2:Slider:SliderDescr:0:10:5:|", @"2:3:Switch:On/Off:", nil]]; 
    
	// Do any additional setup after loading the view, typically from a nib.
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) 
    {
        [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:UITableViewScrollPositionMiddle];
    }
    
    NSLog(@"MasterVC :: DONE Loading View. \n");
}
//////////////////////////////////////////////////////////////////////////////////////////////////							

//////////////////////////////////////////////////////////////////////////////////////////////////
//
- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}
//////////////////////////////////////////////////////////////////////////////////////////////////							

//////////////////////////////////////////////////////////////////////////////////////////////////
//
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}
//////////////////////////////////////////////////////////////////////////////////////////////////							

//////////////////////////////////////////////////////////////////////////////////////////////////
//
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}
//////////////////////////////////////////////////////////////////////////////////////////////////							

//////////////////////////////////////////////////////////////////////////////////////////////////
//
- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}
//////////////////////////////////////////////////////////////////////////////////////////////////							

//////////////////////////////////////////////////////////////////////////////////////////////////
//
- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}
//////////////////////////////////////////////////////////////////////////////////////////////////							

//////////////////////////////////////////////////////////////////////////////////////////////////
//
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
}
//////////////////////////////////////////////////////////////////////////////////////////////////							

#
#
#pragma mark - Msg and notifcation handeling
#
#
//////////////////////////////////////////////////////////////////////////////////////////////////
//
- (void) setupCUAFromGUISpec:(NSNotification *) notification
{
    bool debugCUANotifcation = NO;
    //Make sure it is the right notifcation
    if ([[notification name] isEqualToString:@"SetupCUAFromGUISpec"])
    {
        //Get the object that the notifcation is sending 
        id object = [notification object];
        
        //If it is a string
        if( [object isKindOfClass:[NSString class] ] )
        {
            //report the string
            if( debugCUANotifcation ) NSLog(@"\tCUA :: Spec recv'ed : %@" , object);        
            [self determineGUISpec:object];
        }
    }
    
}
//////////////////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////////////////
//
//
-(void) determineGUISpec:(NSString*) GUISpec
{
    bool debugdetermineGUISpec = NO;
    
    //The seperator that is btn ea UIElement
    NSString* seperator = [NSString stringWithUTF8String:"|"];
    
    //Get each UIElement that is seperated by '|'
    NSArray *UIElementSpecsArray = [ GUISpec componentsSeparatedByString:seperator ];
    
    //Clear the old GUI Table Data
    [self.GUITableData removeAllObjects];
    
    //Add in the new
    [self.GUITableData addObjectsFromArray:UIElementSpecsArray];
    [self.GUITableData removeObjectAtIndex:(self.GUITableData.count-1)];
    
    for( int iTableCell = 0; iTableCell < self.GUITableData.count ; iTableCell++ )
    {
        NSString* cellStr = [self.GUITableData objectAtIndex:iTableCell];
        if( debugdetermineGUISpec ) NSLog(@"\t\t%d : %@" , iTableCell , cellStr);
    }
    
    [self.tableView reloadData];    
    [self.tableView setNeedsLayout];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"DetailVCRedrawCUA" object:nil];
    
}


//////////////////////////////////////////////////////////////////////////////////////////////////
//
- (void) UIElementReaction:(id)sender
{
    NSString *msg;
    
    if( [sender isKindOfClass:[UIButton class] ] )
    {
        UIButton *temp = sender;
        msg = [NSString stringWithFormat:@"gi:%d:1:|", temp.tag];
    }
    else if( [sender isKindOfClass:[UISlider class] ] )
    {
        UISlider *temp = sender;
        msg = [NSString stringWithFormat:@"gi:%d:%d:|", temp.tag , (int)temp.value];
    }
    else if( [sender isKindOfClass:[UISwitch class] ] )
    {
        UISwitch *temp = sender;
        msg = [NSString stringWithFormat:@"gi:%d:%d:|", temp.tag , temp.isOn];
    }
    else 
    {
        msg = [NSString stringWithString:@"CUA :: ERROR : Unhandeled call back "];        
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"TCPClientOmegaSendMsg" object:msg];
    
}
//////////////////////////////////////////////////////////////////////////////////////////////////

#
#
#pragma mark - tableView stuff
#
#
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
//////////////////////////////////////////////////////////////////////////////////////////////////							

//////////////////////////////////////////////////////////////////////////////////////////////////
//
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if( GUITableData == nil ) return 0;
	else return [GUITableData count];
}

//////////////////////////////////////////////////////////////////////////////////////////////////							

//////////////////////////////////////////////////////////////////////////////////////////////////
//
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BOOL debugTabelViewCells = NO;
    if( debugTabelViewCells ) NSLog(@"\tCUA :: Cell Gen :: Loading cells for tableview");
    if( debugTabelViewCells ) NSLog(@"\tCUA :: section : row :: %d:%d" , indexPath.section , indexPath.row);
    
    //Get each UIElement that is seperated by ':'
    NSString* UIElement = [GUITableData objectAtIndex: indexPath.row];
    NSString* seperator = [NSString stringWithUTF8String:":"];
    NSArray *SpecsArray = [ UIElement componentsSeparatedByString:seperator ];
    
    //TODO::Check that the msg coming in is good.
    
    //Element Type 
    CUATypes guiElementType = [ [SpecsArray objectAtIndex:0] integerValue];
    
    //Unique ident
    NSInteger guiElementId = [ [SpecsArray objectAtIndex:1] integerValue];
    
    //Get cell with unique ident 
  	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[NSString stringWithFormat:@"Cell %i",guiElementId]];
    
    //If there is no cell with the specified unique ident
    if (cell == nil)     
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:[NSString stringWithFormat:@"Cell %i" , guiElementId]];        
        if( debugTabelViewCells ) NSLog(@"\t\t Generating new cell : %@ " , [cell reuseIdentifier] );
    }
    
    CGFloat cellH = tableView.rowHeight;
    CGFloat indent = 175;
    
    cell.textLabel.text = [SpecsArray objectAtIndex:2];
    cell.detailTextLabel.text = [SpecsArray objectAtIndex:3];;
    
    if ([cell.contentView subviews])
    {
        for (UIView *subview in [cell.contentView subviews]) 
        {
            [subview removeFromSuperview];
        }
    }
    
    switch (guiElementType)
    {
        case CUA_BUTTON :
        {
            CGFloat buttonH = 35.0;
            CGFloat buttonW = 100;
            CGFloat marginH = (cellH - buttonH) * 0.5;
            
            UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
            [button addTarget:self action:@selector(UIElementReaction:) forControlEvents:UIControlEventTouchDown];
            [button setTitle:[SpecsArray objectAtIndex:4] forState:UIControlStateNormal];
            [button setTag:guiElementId];
            button.frame = CGRectMake(indent, marginH , buttonW , buttonH);
            [cell.contentView addSubview:button];
            break;
        }   
        case CUA_SLIDER :
        {
            CGFloat sliderH = 35.0;
            CGFloat sliderW = 150;
            CGFloat marginH = (cellH - sliderH) * 0.5;
            
            UISlider *slider = [[UISlider alloc] initWithFrame:CGRectMake(indent - 50, marginH, sliderW, sliderH)];
            [slider addTarget:self action:@selector(UIElementReaction:) forControlEvents:UIControlEventValueChanged];
            [slider setBackgroundColor:[UIColor clearColor]];
            [slider setTag:guiElementId];
            slider.minimumValue = [[SpecsArray objectAtIndex:4] integerValue];
            slider.maximumValue = [[SpecsArray objectAtIndex:5] integerValue];
            slider.value = [[SpecsArray objectAtIndex:6] integerValue];
            slider.continuous = NO;
            [cell.contentView addSubview:slider];
            break;
        }   
        case CUA_TOGGLE :
        {
            CGFloat switchH = 35.0;
            CGFloat switchW = 100;
            CGFloat marginH = (cellH - switchH) * 0.5;
            
            UISwitch *toggle = [[UISwitch alloc] initWithFrame:CGRectMake(indent, marginH, switchW, switchH)];
            [toggle addTarget: self action: @selector(UIElementReaction:) forControlEvents:UIControlEventValueChanged];
            [toggle setTag:guiElementId];
            [toggle setOn:[[SpecsArray objectAtIndex:4] integerValue]];
            [cell.contentView addSubview: toggle];
            break;
        }   
    }
    
    //set the colors for the cell
    UIView *background = [[UIImageView alloc] initWithFrame:cell.bounds];
    background.backgroundColor = [UIColor blackColor];
    [cell setBackgroundView:background];
    
    cell.textLabel.textColor = [UIColor whiteColor];
    cell.textLabel.backgroundColor = [UIColor blackColor];
    
    cell.detailTextLabel.textColor = [UIColor whiteColor];
    cell.detailTextLabel.backgroundColor = [UIColor blackColor];
    
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
	
	//TODO::Delete when done : NSLog(@" Section : %d : Index/Row : %d : %@" , [ indexPath indexAtPosition: 0] , [ indexPath indexAtPosition: 1] , [GUITableData objectAtIndex: indexPath.row]);
    
	return cell;
}
//////////////////////////////////////////////////////////////////////////////////////////////////							

//////////////////////////////////////////////////////////////////////////////////////////////////
//
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
	    if (!self.detailViewController) {
	        self.detailViewController = [[DetailViewController alloc] initWithNibName:@"DetailViewController_iPhone" bundle:nil];
	    }
        [self.navigationController pushViewController:self.detailViewController animated:YES];
    }
}

@end
